<template>
	<!-- 系统目录 员工档案 -->
	<div class="box" id="rightCont">
		<!-- main -->
		<div class="main" id="main">
			<!-- left -->
			<div class="main-left">
				<div class="tree">
					<el-tree
					:data="elTree" 
					:props="defaultProps"
					node-key="label"
					:default-expanded-keys="['全部']"
					accordion
					ref="tree"
					:filter-node-method="filterNode"
					@node-click="handleNodeClick"
					class="custom-tree"
					element-loading-spinner="el-icon-more-outline"
					>
					<span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
							:class="node.expanded ? 'el-icon-bumenOpen' : 'el-icon-bumenClose'"></i>
							<i v-else class="el-icon-bumenOpen"></i>
							<span style="margin-left: 8px;">{{ node.label }}</span>
						</span>
					</span>
					</el-tree>
				</div>
			</div>
		<!-- right -->
		<div class="main-right">
			<div class="main-icon">
				<div class="main-icon-a">
					<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #409EFF;color: #fff;"></i>
					<span style="font-size: 14px;font-weight:300;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
				</div>
				<!-- btn1 -->
				<div class="main-icon-zzgl">
					<span style="font-size: 12px;color: #606266;margin-left: 18px;">状态：</span>
					<el-dropdown @command="handleCommand" trigger="click">
						<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
						<el-dropdown-menu slot="dropdown">
						  <el-dropdown-item v-for="(v,i) in selecteds" :key="i" :command="v.command">{{ v.title }}</el-dropdown-item>
						</el-dropdown-menu>
				    </el-dropdown>
				</div>
				<!-- 搜索 -->
				<div class="main-icon-c">
					<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
					<el-autocomplete  popper-class="my-autocomplete" v-model="searchValue" :fetch-suggestions="querySearch" placeholder="编码、员工姓名"
					  size='mini' @select="handleSelect">
					  <i class="el-icon-Ssearch" slot="suffix" style="cursor: pointer;margin-right: 8px;" @click="handleIconClick"></i>
					  <!-- <i class="el-icon-Ssearch" slot="suffix" style="margin-right: 8px;"></i> -->
					  <template slot-scope="{ item }">
						<div class="name" style="font-size: 12px;">{{ item.fullName }}</div>
					  </template>
					</el-autocomplete>
				</div>
				<!-- btn3 -->
				<div class="main-icon-c">
					<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
				</div>
			</div>
			<!-- table -->
			<div class="table">
				<el-table :data="tableData" @row-dblclick="handledbRow" border 
				:max-height="tableHeight" highlight-current-row @current-change="handleCurrentTableChange">
					<!-- 表格行下拉展示 -->
					<el-table-column type="expand" fixed="left">
						<template slot-scope="props">
							<div class="infos">
								<div class="textDes">
									<el-descriptions title="基本信息详情" :column="6" :size="size" border>
										<!-- 开始循环 -->
<!-- 											<el-descriptions-item v-for="(item,index) in tableRows" :key="index">
											<template slot="label"><i class="el-icon-user">{{item.name}}</i></template>{{item.prop}}
										</el-descriptions-item> -->
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-user">员工姓名</i></template>{{props.row.fullName}}
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-phone">联系电话</i></template>{{props.row.contactNumber}}
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">联系地址</i></template>{{props.row.contactAddress}}
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">身份证号码</i></template>{{props.row.idNumber}}
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">民族</i></template>
											<el-tag size="small">{{ props.row.minZu }}</el-tag>
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">政治面貌</i></template>
											<span>{{ props.row.politicalStatus }}</span>
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">工作证件</i></template>
											<div class="imgUrl" style="width: 88px;height: 88px;">
												<img :src="props.row.workIdPhoto" style="width: 100%;height: 100%;">
											</div>
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">手工签名</i></template>
											<div class="imgUrl" style="width: 88px;height: 88px;">
												<img :src="props.row.signatureImage" style="width: 100%;height: 100%;">
											</div>
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">资格证照</i></template>
											<div class="imgUrl" style="width: 88px;height: 88px;">
												<img :src="props.row.qcElectronicImage" style="width: 100%;height: 100%;">
											</div>
										</el-descriptions-item>
										<el-descriptions-item>
											<template slot="label"><i class="el-icon-location-outline">执业证照</i></template>
											<div class="imgUrl" style="width: 88px;height: 88px;">
												<img :src="props.row.pcElectronicImage" style="width: 100%;height: 100%;">
											</div>
										</el-descriptions-item>
									</el-descriptions>
								</div>
							</div>
						</template>
					</el-table-column>
					<!-- fixed -->
					<el-table-column fixed="left" label="行号" type="index"></el-table-column>
					<!-- <el-table-column label="系统序号" prop="id" width="88"></el-table-column> -->
					<el-table-column prop="userCode" sortable label="员工编号" width="128"></el-table-column>
					<el-table-column prop="fullName" sortable label="员工姓名" width="128">
					  <template slot-scope="scope">
					      <span :style="{color: scope.row.sex === '1' ? '#000039' : '#F56C6C'}"> {{ scope.row.fullName }}</span>
					  </template>
					</el-table-column>
					<el-table-column prop="sex" sortable label="性别" width="80">
					  <template slot-scope="scope">
					    <span>
					      <i :class="scope.row.sex === '1' ? 'el-icon-male' : 'el-icon-female'" 
					          :style="{color: scope.row.sex === '1' ? '#000039' : '#F56C6C'}"></i>
					      {{ scope.row.sex === '1' ? '男' : '女' }}
					    </span>
					  </template>
					</el-table-column>
					
					<!-- 身份证号列（脱敏显示） -->
					<el-table-column prop="idNumber" sortable label="身份证号" width="180">
					  <template slot-scope="scope">
					    <span>{{ showFullId ? scope.row.idNumber : maskIdNumber(scope.row.idNumber) }}</span>
					  </template>
					</el-table-column>
					<el-table-column prop="minZu" sortable label="民族" width="88">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ minZuMap[row.minZu] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="professionalTitle" sortable label="专业职称" width="128">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ professMap[row.professionalTitle] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="politicalStatus" sortable label="政治面貌" width="128">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ politicalMap[row.politicalStatus] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="bloodType" sortable label="血型" width="88">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ bloodTypeMap[row.bloodType] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column v-for="(col, inx) in tableRows" sortable :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
					<el-table-column prop="prescriptionRights" label="处方权限" width="88">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ TypeMap[row.prescriptionRights] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="anesthesiaAuthorization" label="麻醉权限" width="88">
						<template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ TypeMap[row.anesthesiaAuthorization] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="surgicalPermission" label="手术权限" width="88">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ TypeMap[row.surgicalPermission] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="poisonPermission" label="毒药权限" width="88">
						 <template slot-scope="{ row }">
							<!-- 根据state显示不同的内容 -->
							<span>{{ TypeMap[row.poisonPermission] || '' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="workIdPhoto" label="工作证件">
						 <template slot-scope="{ row }">
							<!-- iamgesSize -->
							<div class="imgSize" style="width:28px;height:28px;display: flex;margin: auto;">
								<img :src="row.workIdPhoto" style="height: 100%;width: 100%;">
							</div>
						</template>
					</el-table-column>
					<!-- 状态切换列 -->
					<!-- <el-table-column fixed="right" label="可用状态" width="140" align="center">
						<template slot-scope="scope">
						  <el-switch
							size="mini"
							v-model="scope.row.status"
							active-value="1"
							inactive-value="0"
							active-text="启用"
							inactive-text="禁用"
							active-color="#13ce66"
							inactive-color="#ff4949"
							:active-color="scope.row.status === '1' ? '#13ce66' : '#ff4949'"
							@change="handleStatusChange(scope.row)"
							:disabled="scope.row.disabled">
						  </el-switch>
						</template>
					</el-table-column> -->
				</el-table>
				<!-- 分页 -->
				<el-pagination
				style="margin: 12px;"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageNum"
				:page-sizes="[20, 50, 100]"
				:page-size="pageSize"
				:total="totalSize"
				layout="total, sizes, prev, pager, next, jumper"
				background
				>
				</el-pagination>
			</div>
			<!-- feet -->
			<div class="feet" id="feet">
				<div class="feetBtn">
					<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
				</div>
			</div>
		</div>
	</div>
	<!-- messagesBox -->
	<div class="addmessagesBox">
		<addAcc ref="addAcc" @childEvent="aa"></addAcc>
	</div>
	<div class="moreTool">
		<!-- 高级设置对话框 -->
		<el-dialog title="高级设置" :visible.sync="advancedDialogVisible" width="30%">
		  <el-form label-width="120px">
		    <el-form-item label="身份证显示模式">
		      <el-switch
		        :value="showFullId"
		        active-text="完整显示"
		        inactive-text="脱敏显示"
		        @change="handleSwitchChange">
		      </el-switch>
		    </el-form-item>
		  </el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="advancedDialogVisible = false" size="mini">关闭</el-button>
		  </span>
		</el-dialog>
	</div>
	</div>
</template>

<script>
	// son 
	import addAcc from "./AccListSon/addAcc.vue";
	// selfs / js
	import Chinese from "@/external/PY.js";
	import Pinyin from "@/external/pinyin.js";
	// import box from '../../external/box.js'
	// // 接口
	import { selectList,dict,updateStatus } from "@/api/staff/staff.js";
	import { findAttribute } from "@/api/user.js";
	export default {
		watch: {
		  showFullId(newVal, oldVal) {
		    // 只有当值真正变化时才触发
		    if (newVal !== oldVal) {
		      this.handleIdDisplayChange(newVal);
		    }
		  }
		},
		components: {
			addAcc
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				watch:'查看',
				searchValue:'',
				status:1,
				tableHeight:'570', // table的高度，以便超出高度显示滚动条
				currentHeight:'', // 用于计算table的高度，以便超出高度显示滚动条
				windowWidth: '', //表格自适应宽度
				toCodeNum:'0000',//拼接自增 导零
				iconHandleClick:'el-icon-plus',
				CatalogueName:'员工档案',
				elName:'',
				DropDownedName:'可用',
				typeValue:'',
				YNuseVaule:'可用',
				nowDateTimeValue:'',
				iconComes:'el-icon-dangan',
				operatingTime:'',
				// boolean
				disabled:true,
				noEidt:true,
				formdisabled:true,
				loading:false,
				dialogVisible:false,	//此乃查看/编辑控制
				addDialogVisible:false, //此乃新增控制
				// number
				dataIndex: 0,
				CodeNumber:0,
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 10, //总条数
				// arr
				data: [],
				oop:[],
				userInfo: [],
				watchData: [],
				tableData: [],
				currentTable:[],  // 表格单选
				restaurants: [], // 搜索关键字
				showFullId: false, // 控制是否显示完整身份证号
				advancedDialogVisible: false, // 高级设置对话框
				password: '', // 密码输入
				passwordError: false, // 密码错误标志
				selecteds:[ { title:"可用", command:"a" },{ title:"禁用", command:"b" } ],
				YNuse:[{ id:1,label:'可用',value:'1'},{ id:2,label:'禁用',value:'2'}],
				drugTypeOptions:[{ id:1,label:'毒麻类',value:'毒麻类'},{ id:2,label:'精神类',value:'精神类'}],
				elTree:[{ label: '全部', path:'', title:'', icon:'el-icon-news',children:[]}],
				PoliticalOptions:[
					{id: 1, label: "中共党员"},{id: 2,label: "中共预备党员"},{id: 3,label: "共青团员"},{id: 4,label: "民革党员"},
					{id: 5,label: "民盟盟员"},{id: 6, label: "民建会员"},{ id: 7,label: "民进会员"},{id: 8,label: "农工党党员"},
					{id: 9,label: "致公党党员"},{id: 10,label: "九三学社社员"},{id: 11,label: "台盟盟员"},{id: 12,label: "无党派人士"},{id: 13,label: "群众"},
				],
				// title右侧按钮
				headerBtn:[
				 { refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
				 { senior:"senior", title:"高级", type:"primary", icon:"" },
				 // { add:"add", title:"新增", type:"warning" },
				],
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					// { title:"新增西成药",icon:"el-icon-adds", type:"primary" },
					// { title:"修改西成药",icon:"el-icon-edit", type:"primary" },
					{ title:"查看",icon:"el-icon-watch", type:"primary" },
					// { title:"删除",icon:"el-icon-del", type:"danger" },
					// { title:"目录引用",icon:"el-icon-closeFiles", type:"primary" },
					{ title:"打印",icon:"el-icon-ggml", type:"primary" },
					{ title:"导出",icon:"el-icon-export", type:"primary" },
					{ title:"关闭",icon:"el-icon-close", type:"primary" },
				],
				// 最终使用的按钮数组
				feetBtn: [],
				professionalOptions: [],
				minZuMap:{
					1: '数据不对，默认admin',
					// ...待接口响应
				},
				politicalMap:{
					1: '数据不对，默认admin',
					// ...待接口响应
				},
				bloodTypeMap:{
					1: '数据不对，默认admin',
					// ...待接口响应
				},
				professMap:{
					1: '数据不对，默认admin',
					// ...待接口响应
				},
				TypeMap:{
					'0': '否',
					'1': '是',
					// ...待接口响应
				},
				// title右侧按钮
				tableRows:[
					{ name:"员工编码", prop:"userCode", nz:"nz" },
					{ name:"出生日期", prop:"brdy", type:"" },{ name:"农历生日", prop:"lunarBrdy", type:"" },
					{ name:"隶属科室", prop:"deptName", nz:"nz" },{ name:"执业证号", prop:"practicingNumber", type:"" },
					{ name:"资格证书编号", prop:"qualificationNumber", type:"" },{ name:"贯标码", prop:"standardCode", type:"" },
					{ name:"贯标名称", prop:"standardName", type:"" },
				],
				
			};
		},
		computed: {
		    // 格式化数字，确保4个0后的数字自增时不会出现前导零
		    formattedNumber() {
				return '00000' + this.toCodeNum.toString().slice(1);
		    },
		},
		inject: ['reload'], // 无痕刷新
		mounted() {
			this.loadData();
			// this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
			// this.addForm.operator = this.userInfo.userName
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				//  获取字典数据
				this.getditc();
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
				this.currentHeight = this.$getHeights();
				this.getTableHeight();
			})
			this.nowDateTime();
			// this.$handlePermissions(); // 引入全局自定义封装方法
			this.initButtons(); // 引入全局自定义封装方法
		},
		methods: {
		   // 数据源 
		    async loadData(){
			   let res = await selectList({
				   status: this.status,
				   fullName:this.searchValue,
				   deptName:this.elName,
				   pageNum: this.pageNum,
				   pageSize: this.pageSize
			   })
			    this.totalSize = res.data.totalSize;
				this.tableData = res.data.content.map(item => {
				    return {
				      ...item,
				      showFullId: false // 初始化为不显示完整身份证号
				    }
				});
				console.log(this.tableData,'snoasooipjewfnu');
			    this.restaurants = res.data.content;
				// 左侧树菜单的科室
				let keDatas = await findAttribute();
				this.elTree[0].children = keDatas.data.map(v=>{ return { label: v.deptName , ...v }})
			},
			/*
				about tree
			*/
			handleNodeClick(data,e) {
				this.CatalogueName = data.title
				this.iconComes = 'el-icon-' + this.makePy(data.label)
				this.loadData();
			},
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
			},
			// 字典数据
			async getditc(){
			   this.result = await dict();
			   // console.log(this.result.data);
			   // 设置本地存储
			   localStorage.setItem('dict', JSON.stringify(this.result.data));
			   // 将 政治面貌 转换为 politicalMap 格式
			   this.politicalMap = this.PoliticalOptions.reduce((map, item) => {
			   	map[item.id] = item.label;  // 使用 id 作为键，label 作为值
			   	return map;
			   }, { 1: '数据不对，默认admin' });  // 保留初始值
			   //  证件类型
			   this.idType = this.result.data.certypeEntities.map(v=>{ return { label: v.name , ...v }});
			   //  专业职称
			   this.professionalOptions = this.result.data.profttlEntities.map(v=>{ return { label: v.name , ...v }});
			   // 将 专业职称 转换为 politicalMap 格式
			   this.professMap = this.professionalOptions.reduce((map, item) => {
			   	map[item.id] = item.label;  // 使用 id 作为键，label 作为值
			   	return map;
			   }, { 1: '数据不对，默认admin' });  // 保留初始值
			   //  民族
			   this.MZOptions = this.result.data.natyEntities.map(v=>{ return { label: v.name , ...v }});
			   // 将 民族 转换为 minZuMap 格式
			   this.minZuMap = this.MZOptions.reduce((map, item) => {
			   	map[item.id] = item.label;  // 使用 id 作为键，label 作为值
			   	return map;
			   }, { 1: '数据不对，默认admin' });  // 保留初始值
			   //  婚姻状况
			   this.marryiedOptions = this.result.data.mrgStateEntities.map(v=>{ return { label: v.name , ...v }})
			   //  血型
			   this.bloodOptions = this.result.data.aboTypeEntities.map(v=>{ return { label: v.name , ...v }});
			   this.bloodTypeMap = this.bloodOptions.reduce((map, item) => {
			   	map[item.id] = item.label;  // 使用 id 作为键，label 作为值
			   	return map;
			   }, { 1: '数据不对，默认admin' });  // 保留初始值
			   // 暂时过滤掉RH阴性和RH阳性的选项
			   this.bloodOptions = this.bloodOptions.filter(item =>
			     item.name !== 'RH阳性' && item.name !== 'RH阴性'
			   );
			},
			aa(){
				// this.loadData();
			},
			// 身份证号脱敏处理
			maskIdNumber(idNumber) {
			    if (!idNumber || idNumber.length < 8) return idNumber;
			    const prefix = idNumber.substring(0, 3);
			    const suffix = idNumber.substring(idNumber.length - 4);
			    return `${prefix}${'*'.repeat(idNumber.length - 7)}${suffix}`;
			},
			
			// 高级按钮点击事件
			  handleAdvancedClick() {
			    this.advancedDialogVisible = true;
			  },

			// 处理身份证显示模式变化
			// 处理开关状态变化
			  handleSwitchChange(newValue) {
			    if (newValue) {
			      // 如果要显示完整身份证号，需要验证密码
			      this.$confirm('显示完整身份证号需要验证身份，请输入密码：', '验证身份', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',
			        inputType: 'password',
			        inputPlaceholder: '请输入密码',
			        showInput: true,
			        beforeClose: (s, instance, done) => {
			          if (s === 'confirm') {
			            if (instance.inputValue === '123456') {
			              // 密码正确，更新状态为显示完整身份证号
			              this.showFullId = true;
			              done();
			            } else {
			              this.$message.error('密码错误');
			              // 保持开关状态为脱敏显示
			              done();
			              // 不关闭弹窗，让用户重新输入
			              return false;
			            }
			          } else {
			            // 取消操作，保持开关状态为脱敏显示
			            done();
			          }
			        }
			      }).catch(() => {
			        // 取消操作或密码错误，保持开关状态为脱敏显示
			      });
			    } else {
			      // 关闭脱敏不需要验证，直接更新状态
			      this.showFullId = false;
			    }
			  },
			// 根据状态设置行样式
			tableRowClassName({row}) {
			  return row.status === '0' ? 'disabled-row' : '';
			},
			// 表格单选
			handleCurrentTableChange(val){
				this.currentTable = val
			},
			// props
			querySearch(queryString, cb) {
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				clearTimeout(this.timeout);
				this.timeout = setTimeout(() => {
				  cb(results);
				}, 888 * Math.random());
			},
			createFilter(queryString) {
				return (restaurant) => {
				  return (restaurant.fullName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			handleIconClick(ev) {
				this.loadData();
			},
			handleSelect(item) {
				this.searchValue = item.fullName
				this.loadData();
			},
			// 用于计算table的高度，以便超出高度显示滚动条
			getTableHeight(){
				let headerHeight = this.currentHeight.mainHeight
				let feetHeight = this.currentHeight.feetHeight
				let lastHeight = this.currentHeight.lastHeight
				this.tableHeight = this.currentHeight.rightContentHeight - feetHeight * 3
				console.log(this.tableHeight,'this.tableHeightthis.tableHeight');
			},
			/*
				about table
			*/
		   // col 里面包含了表头字段和名称，list 是表格数据
		   columnWidth(col, list) {
			 let prop = col.prop,lab = col.lab;
			 let width = 40; // 设定一个最小值
			 let maxlenStr = ""; // 最长字符串
			 for (let info of list) {
			   if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
			 }
			 width = Math.max(width, len(lab), len(maxlenStr));
			 // 表格自带的内边距(20px) 自调
			 return width + 12; // 这里加了 12px
			 function len(str) {
			   // 实际分配长度可根据需要自行调整
			   let length = 18;
			   for (const char of str + "") {
				 // 英文小写字符 8px
				 if ("a" <= char && char <= "z") length += 8;
				 // 英文大写字符 8px
				 else if ("A" <= char && char <= "Z") length += 8;
				 // 中文字符 28px
				 else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
				 // 其他 8px
				 else length += 8;
			   }
			   return length;
			 }
		   },
			// edit table
			//新增保存
			addNewData(){
				// let res = await addPoisonAnesthesia(this.addForm)
				console.log(this.addForm);
				//触发验证表单
				this.$refs.addForm.validate(async(valid) => {
				  if(valid){
				    //验证通过
				    // console.log('submit');
				    let res = await addPoisonAnesthesia(this.addForm)
				    console.log(res);
					if (res.code === 200){
					this.$message({
						message:res.message,
						type:"success"
					});
					this.loadData(); //更新数据驱动
					}else{
					  //验证失败
					  console.log('失败');
					}
				}
				});
			},
			// 打印按钮点击事件
			handlePrint() {
			  this.$confirm('请选择打印方式', '打印设置', {
			    confirmButtonText: 'Lodop打印',
			    cancelButtonText: '浏览器打印',
			    type: 'warning'
			  }).then(() => {
			    // 用户选择Lodop打印
				console.log('用户选择Lodop打印');
			    this.printWithLodop();
			  }).catch(() => {
			    // 用户选择浏览器打印
			    // this.printWithBrowser()
				console.log('用户选择浏览器打印');
			  })
			},
			// 使用Lodop打印并设计
			printWithLodop() {
				  // 准备表格数据
				  const tableData = this.tableData.map(item => {
				    return {
				      ...item,
				      // 添加任何需要转换的字段
				    };
				  });
				  
				  // 准备当前选中行数据
				  const currentTable = this.currentTable;
				  
				  this.$router.push({
				    path: '/PrintTemplateDesigner',
				    query: {
				      tableData: JSON.stringify(tableData),
				      currentTable: JSON.stringify(tableData),
				      templateName: this.CatalogueName
				    }
				});
			},
			// input 
			inputLabel(){
				this.addForm.code = this.makePy(this.addForm.label).toLocaleUpperCase().slice(0,1) + this.formattedNumber + this.CodeNumber;//编码
				this.addForm.textSpell = this.makePy(this.addForm.label).toLocaleUpperCase();//拼音简码
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			// db events
			handledbRow(row, column, event){
				if(row){ 
					row.nameTitle = '查看'
					this.$refs.addAcc.openModel(row);
				}
				// console.log(this.form);
				this.formdisabled = true
				this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
				// console.log(this.form.textSpell);
			},

			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
					this.loading = true;
						setTimeout(() => {
							this.reload();
							this.loading = false;
						}, 1500)
						break;
					case 1:
						// 处理索引1的逻辑
						this.handleAdvancedClick();
						break;
					case 2:
						// 处理索引2的逻辑 => 新增 -> 调用子组件
						// this.$refs.addAcc.openModel();
						break;
				}
			},
			handleCommand(command) {
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '可用';
				  this.status = 1;
				  this.loadData();
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '禁用';
				  // this.tableData = 
				  this.status = 0;
				  this.loadData();
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.DropDownedName = '全部'
				  break;
				// ... 其他 case
			  }
			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 288;
			},
			// 系统当前日期时间
			nowDateTime(){
				const now = new Date(); //创建时间日期对象
				const year = now.getFullYear(); //年
				const month = now.getMonth() + 1; //月份是从0开始的
				const day = now.getDate(); //日
				const hours = now.getHours(); //小时
				const minutes = now.getMinutes(); //分钟
				const seconds = now.getSeconds(); //秒
				const currentDate = `${year}-${month}-${day}`.replace(/-/g, '') //替换操作
				this.nowDateTimeValue = `${year}-${month}-${day}` + ` ` + `${hours}:${minutes}:${seconds}`
				// this.datetimesinglend = 
				// 将字符串转换为Date对象
				// console.log(this.nowDateTimeValue);
			},
			// 表格底部循环按钮事件
			feetHandClick(v){
				console.log(v);
				// i event
				// 处理逻辑 => 新增
				if(v.title == '新增'){
					// 处理索引2的逻辑 => 新增 -> 调用子组件
					this.nameTitle = '新增'
					this.$refs.addAcc.openModel(this.nameTitle);
				}
				// 在feetHandClick方法中修改修改按钮的逻辑
				else if (v.title == '修改'){
				  if(this.currentTable.length != 0){
				    this.currentTable.nameTitle = '修改'
				    // 添加一个标志表示是修改操作
				    this.currentTable.isEdit = true
				    this.$refs.addAcc.openModel(this.currentTable);
				  }else{
				    this.$message({ type: 'warning', message: '请先选择一条数据'});
				  }
				}
				
				// 处理逻辑 => 查看
				else if(v.title == '查看'){
					// 处理索引1的逻辑 => 修改
					if(this.currentTable.length != 0){
						this.currentTable.nameTitle = '查看'
						this.$refs.addAcc.openModel(this.currentTable);
					}else{
						this.$message({ type: 'warning', message: '请先选择一条数据'});
					}
					
				}
				// 处理逻辑 => 打印
				else if(v.title === '打印'){
					this.handlePrint();
				}
				// 处理逻辑 => 导出
				else if(v.title === '导出'){
					this.$confirm('敬请期待')
					.then(_ => {})
					.catch(_ => {});
				}
				// 处理逻辑 => 关闭
				else{
					setTimeout(() =>{
						window.history.back();
					},888)
				}
			},
			// 过滤器
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			// 添加一个方法来处理子组件传回的修改数据
			handleUpdateData(updatedData) {
			  // 调用修改接口
			  updateStaff(updatedData).then(res => {
			    if(res.code === 200) {
			      this.$message.success('修改成功')
			      this.loadData() // 重新加载数据
			    }
			  })
			}
			
		}
	}
</script>

<style lang="less" scoped>
	.box {
	  height: calc(100vh - 90px); // 减去导航栏高度
	  width: 100%;
	  overflow: hidden;
	
		/deep/ .el-table {
	    width: 100% !important;
	    
	    .el-table__body-wrapper {
	      overflow-x: auto !important;
	    }
	    
	    .el-table__header-wrapper {
	      overflow-x: hidden !important;
	    }
		/* 小眼睛图标样式 */
		.el-icon-watch {
		  color: #409EFF;
		  &:hover {
		    color: #66b1ff;
		  }
		}
		.el-icon-shield {
		  color: #F56C6C;
		  &:hover {
		    color: #f78989;
		  }
		}
	}
	/deep/ .el-switch__label *{
		font-size: 12px;
	}
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		background-color: #f1f1f1;
		border: none;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	    width: 100%;
	    // height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/* 自定义高亮颜色 */
	::v-deep .el-table__body tr.current-row > td {
	  background-color: #80b7ff !important;
	  color: #f9f9f9; /* 可选：修改文字颜色 */
	}
	  .main {
	    display: flex;
	    height: 100%;
	    width: 100%;
	
	    // 左侧树形菜单
	    .main-left {
	      width: 128px;
	      height: 100%;
	      background: #f5f7fa;
	      border-right: 1px solid #e6e6e6;
	      overflow-y: auto;
	      scrollbar-width: none; /* Firefox */
	      -ms-overflow-style: none; /* IE 10+ */
	      
	      &::-webkit-scrollbar {
	        display: none; /* Chrome Safari */
	      }
		
	      /deep/ .el-tree {
	        height: 100%;
	        .el-tree-node__content {
	          height: 36px;
	        }
	      }
		  /* 树形结构节点添加连线 */
		  /deep/  .tree .el-tree-node {
		      position: relative;
		      // padding-left: 16px;
		    }
		  
		  /deep/  .tree .el-tree-node :last-child:before {
		      height: 38px;
		    }
		  
		  /deep/  .tree .el-tree > .el-tree-node:before {
		      border-left: none;
		    }
		    .tree-container .el-tree > .el-tree-node:after {
		      border-top: none;
		    }
		  
		  /deep/  .tree .el-tree-node__children .el-tree-node:before {
		      content: '';
		      left: 12px;
		      position: absolute;
		      right: auto;
		      border-width: 1px;
		    }
		  /deep/  .tree .el-tree-node__children {
		  	padding-left: 0px;
		    }
		  /deep/  .tree .el-tree-node:after {
		      content: '';
		      left: 12px;
		      position: absolute;
		      right: auto;
		      border-width: 1px;
		    }
		  /deep/  .tree .el-tree-node__expand-icon.is-leaf {
		      display: none;
		    }
		  
		   /deep/ .tree .el-tree-node:before {
		      border-left: 1px dashed #dddddd;
		      bottom: 0px;
		      height: 100%;
		      top: -26px;
		      width: 1px;
		    }
		  
		  /deep/  .tree .el-tree-node:after {
		      border-top: 1px dashed #dddddd;
		      height: 20px;
		      top: 12px;
		      width: 24px;
		    }
	    }
	    
	    // 右侧内容区域
	    .main-right {
	      flex: 1;
	      display: flex;
	      flex-direction: column;
	      height: 100%;
	      overflow: hidden;
	      
	      // 顶部搜索区域
		.main-icon {
			display: flex;
			align-items: center;
			padding: 12px;
			line-height: 40px;
			.main-icon-a{
				// width: 240px;
				// background-color: #00557f;
			}
			.main-icon-b{
				margin-left: 28px;
				/deep/ .el-dropdown{
					font-size: 12px;
					cursor: pointer;
				}
				/deep/ .el-dropdown:hover {
					font-weight: bold;
					color: #66b1ff;
				}
				/deep/ .el-icon--right{
					// background-color: #66b1ff;
				}
				/deep/ .el-popper[x-placement^=bottom]{
					margin-top: 0;
				}
			}
			// c
			.main-icon-c{
				display: flex;
				align-items: center;
				margin-left: 28px;
				/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
					width: 80%;
				}
			}
		}
	      
		// 表格容器（带滚动）
		.table {
	        flex: 1;
			width: 100%;
	        overflow: hidden;
	        display: flex;
	        flex-direction: column;
			/deep/ .el-pagination {
				margin: 12px;
			}
	    }
	      
	      // 底部固定区域
	      .feet {
	        height: 40px;
	        display: flex;
			align-items: center;
	        padding: 12px;
	        background: #fff;
	        border-top: 1px solid #e6e6e6;
	        flex-shrink: 0;
	        
	        .feetBtn {
	          gap: 8px;
	        }
			
	        }
	    }
	  }
		.moreTool{
			/* 高级设置对话框样式 */
			/deep/ .el-dialog__header {
			  background-color: #007bb0;
			  padding: 12px;
			}
			
			/deep/ .el-dialog__title {
			  color: #fff;
			  font-size: 14px;
			}
			
			/deep/ .el-dialog__headerbtn .el-dialog__close {
			  color: #fff;
			}
			
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover {
			  background-color: brown;
			}
		}
		.addModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
		.editModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
	}

</style>